package config

import (
	"fmt"
	"os"
	"x-admin/backend/pkg/logger"

	"gopkg.in/yaml.v3"
)

// Config 应用配置
type Config struct {
	App      AppConfig      `yaml:"app"`
	Database DatabaseConfig `yaml:"database"`
	JWT      JWTConfig      `yaml:"jwt"`
	Redis    RedisConfig    `yaml:"redis"`
	Log      LogConfig      `yaml:"log"`
	Storage  StorageConfig  `yaml:"storage"`
}

// AppConfig 应用配置
type AppConfig struct {
	Name string `yaml:"name"`
	Mode string `yaml:"mode"`
	Port string `yaml:"port"`
	Host string `yaml:"host"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Driver   string `yaml:"driver"`
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Charset  string `yaml:"charset"`
	SSLMode  string `yaml:"ssl_mode"`
}

// JWTConfig JWT配置
type JWTConfig struct {
	Secret     string `yaml:"secret"`
	ExpireTime int    `yaml:"expire_time"`
	Issuer     string `yaml:"issuer"`
}

// RedisConfig Redis配置
type RedisConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
	Database int    `yaml:"database"`
}

// LogConfig 日志配置
type LogConfig struct {
	Level       string `yaml:"level"`
	Format      string `yaml:"format"`
	Output      string `yaml:"output"`
	FilePath    string `yaml:"file_path"`
	Filename    string `yaml:"filename"` // 兼容旧配置
	MaxSize     int    `yaml:"max_size"`
	MaxBackups  int    `yaml:"max_backups"`
	MaxAge      int    `yaml:"max_age"`
	Compress    bool   `yaml:"compress"`
	ShowCaller  bool   `yaml:"show_caller"`
	Environment string `yaml:"environment"`
}

// StorageConfig 存储配置
type StorageConfig struct {
	Driver        string `yaml:"driver"`         // local, oss, s3
	LocalDir      string `yaml:"local_dir"`      // 本地存储目录
	BaseURL       string `yaml:"base_url"`       // 访问基础URL
	HashAlgorithm string `yaml:"hash_algorithm"` // 哈希算法: md5, sha256
	// OSS配置 (预留)
	OSSConfig OSSConfig `yaml:"oss"`
}

// OSSConfig 阿里云OSS配置 (预留)
type OSSConfig struct {
	Endpoint        string `yaml:"endpoint"`
	AccessKeyID     string `yaml:"access_key_id"`
	AccessKeySecret string `yaml:"access_key_secret"`
	BucketName      string `yaml:"bucket_name"`
	Domain          string `yaml:"domain"`
}

// Load 加载配置
func Load() (*Config, error) {
	// 默认配置
	config := &Config{
		App: AppConfig{
			Name: "X-Admin",
			Mode: "debug",
			Port: "8080",
			Host: "localhost",
		},
		Database: DatabaseConfig{
			Driver:   "mysql",
			Host:     "localhost",
			Port:     3306,
			Username: "root",
			Password: "root123456",
			Database: "x_admin",
			Charset:  "utf8mb4",
			SSLMode:  "disable",
		},
		JWT: JWTConfig{
			Secret:     "x-admin-secret-key",
			ExpireTime: 7200, // 2小时
			Issuer:     "x-admin",
		},
		Redis: RedisConfig{
			Host:     "localhost",
			Port:     6379,
			Password: "",
			Database: 0,
		},
		Log: LogConfig{
			Level:       "info",
			Format:      "text",
			Output:      "console",
			FilePath:    "logs/app.log",
			MaxSize:     100,
			MaxBackups:  3,
			MaxAge:      7,
			Compress:    true,
			ShowCaller:  true,
			Environment: "development",
		},
		Storage: StorageConfig{
			Driver:        "local",
			LocalDir:      "uploads",
			BaseURL:       "http://localhost:8080/uploads",
			HashAlgorithm: "sha256",
		},
	}

	// 从环境变量覆盖配置
	loadFromEnv(config)

	// 从配置文件加载
	configFile := "config/app.yaml"
	if _, err := os.Stat(configFile); err == nil {
		data, err := os.ReadFile(configFile)
		if err != nil {
			return nil, fmt.Errorf("读取配置文件失败: %w", err)
		}

		if err := yaml.Unmarshal(data, config); err != nil {
			return nil, fmt.Errorf("解析配置文件失败: %w", err)
		}
	}

	return config, nil
}

// loadFromEnv 从环境变量加载配置
func loadFromEnv(config *Config) {
	if port := os.Getenv("PORT"); port != "" {
		config.App.Port = port
	}
	if mode := os.Getenv("GIN_MODE"); mode != "" {
		config.App.Mode = mode
	}
	if dbHost := os.Getenv("DB_HOST"); dbHost != "" {
		config.Database.Host = dbHost
	}
	if dbUser := os.Getenv("DB_USER"); dbUser != "" {
		config.Database.Username = dbUser
	}
	if dbPassword := os.Getenv("DB_PASSWORD"); dbPassword != "" {
		config.Database.Password = dbPassword
	}
	if dbName := os.Getenv("DB_NAME"); dbName != "" {
		config.Database.Database = dbName
	}
	if jwtSecret := os.Getenv("JWT_SECRET"); jwtSecret != "" {
		config.JWT.Secret = jwtSecret
	}
	if redisHost := os.Getenv("REDIS_HOST"); redisHost != "" {
		config.Redis.Host = redisHost
	}
	if redisPassword := os.Getenv("REDIS_PASSWORD"); redisPassword != "" {
		config.Redis.Password = redisPassword
	}
}

// ToLoggerConfig 将 LogConfig 转换为 logger.Config
func (lc *LogConfig) ToLoggerConfig() *logger.Config {
	// 兼容性处理：如果 FilePath 为空但 Filename 不为空，使用 Filename
	filePath := lc.FilePath
	if filePath == "" && lc.Filename != "" {
		filePath = lc.Filename
	}

	return &logger.Config{
		Level:       lc.Level,
		Format:      lc.Format,
		Output:      lc.Output,
		FilePath:    filePath,
		MaxSize:     lc.MaxSize,
		MaxBackups:  lc.MaxBackups,
		MaxAge:      lc.MaxAge,
		Compress:    lc.Compress,
		ShowCaller:  lc.ShowCaller,
		Environment: lc.Environment,
	}
}
